package net.moonbiter.ebs.exposer;

import javax.naming.ConfigurationException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.moonbiter.ebs.ServiceCaller;
import net.moonbiter.ebs.ServiceDef;
import net.moonbiter.ebs.ServicesRegister;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class EsperantoSpringController implements Controller {
	private ServiceCaller<HttpServletRequest, HttpServletResponse> serviceCaller;
	private ServicesRegister servicesRegister;
	private String baseUri;
	
	private final static Logger logger = Logger.getLogger(EsperantoSpringController.class);
	
	public EsperantoSpringController(ServiceCaller<HttpServletRequest, HttpServletResponse> serviceCallerValue, ServicesRegister register, String baseUriValue){
		serviceCaller = serviceCallerValue;
		servicesRegister = register;
		baseUri = baseUriValue;
		/*File tmpFilesDir = new File(config.getServletContext().getRealPath("/WEB-INF/temp"));
		if (!tmpFilesDir.exists()){
			if (!tmpFilesDir.mkdir()){
				throw new ServletException("Can't create the directory for temporary uploaded files");
			}
		}*/
	}
	
	@Override
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		//serviceCaller.execute(inputs, output, service);
		String contextPath = request.getContextPath();
		String completeUri = request.getRequestURI();
		String completeBase = contextPath+baseUri;
		if (!completeUri.startsWith(completeBase)){
			throw new ConfigurationException("Bad base uri specified (base uri:"
					+baseUri+", context path: "+contextPath+", uri requested: "+completeUri+")");
		}
		String relativeUri = completeUri.substring(completeBase.length());
		logger.debug("Processing request : \""+relativeUri+"\"");
		
		String[] portions = relativeUri.split("/");
		if (portions.length<3) {
			logger.debug("Uri is not conforming to a service request pattern, I ignore it");
			response.setStatus(HttpServletResponse.SC_NOT_FOUND);
			return null;
		}
		
		String providerName = portions[1];
		String serviceName = portions[2];
		
		if (!servicesRegister.hasService(providerName, serviceName)){
			logger.debug("Required unexisting service, providerName=\""
					+providerName+"\", serviceName=\""+serviceName+"\"");
			response.setStatus(HttpServletResponse.SC_NOT_FOUND);
			return null;
		} else {
			logger.debug("Required existing service, providerName=\""
					+providerName+"\", serviceName=\""+serviceName+"\"");
			ServiceDef serviceDef = servicesRegister.getService(providerName, serviceName);
			
			serviceCaller.execute(request, response, serviceDef);
			return null;
		}
	}

}
